from flask import Flask, jsonify, render_template
from dotenv import load_dotenv
import os
from routes.api import api_bp
import logging
from flask_cors import CORS

# 加载环境变量
load_dotenv()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

def create_app():
    """应用工厂函数"""
    app = Flask(__name__, 
                template_folder='templates',
                static_folder='static')
    
    # 配置
    app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'dev-secret-key')
    app.config['DEBUG'] = os.getenv('FLASK_DEBUG', 'True').lower() == 'true'
    
    # 根路由 - 返回HTML页面
    @app.route('/')
    def home():
        return render_template('index.html')
    
    # 注册蓝图
    try:
        app.register_blueprint(api_bp, url_prefix='/api')
        print("✅ API蓝图注册成功")
        
        # 打印所有路由（调试用）
        print("📋 注册的路由:")
        for rule in app.url_map.iter_rules():
            print(f"  {rule.methods} {rule.rule}")
            
    except ImportError as e:
        print(f"❌ 导入API蓝图失败: {e}")
    
    @app.route('/static/components/<path:filename>')
    def serve_component(filename):
        """提供组件文件服务"""
        from flask import send_from_directory
        return send_from_directory('templates/components', filename)
    
    return app

app = create_app()
CORS(app)

if __name__ == '__main__':
    print("🚀 启动Flask应用...")
    app.run(host='0.0.0.0', port=5000, debug=True) 